<template>
  <a-form-model ref="form" :model="formData">
    <a-divider orientation="left"> 采购信息 </a-divider>
    <a-form-model-item
      label="采购人"
      prop="buyer"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :rules="[{ required: true, message: '请选择采购人!' }]"
    >
      <j-url-select
        v-model="formData.buyer"
        placeholder="请选择"
        optionLabel="username"
        url="/sys/user/getAllUserByOrg"
      />
    </a-form-model-item>
    <a-form-model-item label="备注" prop="remark" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-textarea v-model="formData.remark" rows="4" placeholder="请输入" :maxLength="128" />
    </a-form-model-item>
    <a-divider orientation="left"> 供应商信息 </a-divider>
    <a-alert
      message="采购时默认选择此处的默认供应商进行采购，请及时谨慎维护此处信息。"
      banner
      style="margin-bottom: 10px"
    />
    <a-button
      type="primary"
      icon="plus"
      @click="
        defaultLink = ''
        show1688Modal = true
      "
      style="margin-right: 10px"
      >新增1688供应商</a-button
    >
    <a-button type="primary" icon="plus" @click="addOtherSupplier">新增其它供应商</a-button>
    <a-table
      :pagination="false"
      bordered
      :columns="formColumns"
      :scroll="{ x: true }"
      :data-source="formData.tableData"
      rowKey="sortNum"
      class="supplier-table"
      ref="buyerTable"
    >
      <template #sortSlot>
        <a-icon type="menu" class="sort-handler-ico" title="拖动排序" />
      </template>
      <template #defaultTitle> <span class="required-ico">*</span>默认 </template>
      <template #defaultSlot="text, record, index">
        <a-radio :checked="!!record.izDefault" @click="setDefault(index)">默认</a-radio>
      </template>
      <template #typeSlot="text, record">
        <a-tag v-if="record.type == 1" color="green"> 1688 </a-tag>
        <a-tag v-else color="orange"> 其他 </a-tag>
      </template>
      <template #nameTitle> <span class="required-ico">*</span>供应商名称 </template>
      <template #nameSlot="text, record, index">
        <span v-if="record.type == 1">
          {{ record.name }}
        </span>
        <div v-else>
          <a-form-model-item
            :prop="'tableData.' + index + '.supplierId'"
            :rules="{
              required: true,
              message: '供应商不能为空',
              trigger: 'change',
            }"
          >
            <j-url-select-search
              placeholder="请输入供应商名称"
              v-model="record.supplierId"
              :allowClear="false"
              url="/hzkj-product/product/productLibrary/supplier/list?pageNo=1&pageSize=10"
              :optionDiy="optionDiy"
              @change="supplierNameChange(record, arguments)"
            />
            <a-button type="link" @click="showOtherModal = true">新增</a-button>
          </a-form-model-item>
        </div>
      </template>
      <template #linkSlot="text, record">
        <div v-if="record.type == 1">
          <div>商品：{{ record.proName }}</div>
          <div class="link-item">
            <span>链接：</span>
            <a-tooltip :overlayStyle="{ 'min-Width': '600px' }">
              <template slot="title"> {{ record.url || '-' }} </template>
              <div class="link">
                <a :href="record.url" target="_blank">{{ record.url }}</a>
              </div>
            </a-tooltip>
            <a-button type="link" class="copy-btn" icon="copy" @click="copyTo(record.url)" title="复制"></a-button>
          </div>
        </div>
        <a-input v-else v-model="record.url" placeholder="请输入"></a-input>
      </template>
      <template #attrSlot="text, record">
        <div v-if="record.type == 1">
          <div v-for="item1 in record.attribute" :key="item1.attributeID">
            {{ item1.attributeName }}：<span v-for="(val2, index2) in item1.checkVal" :key="index2">{{ val2 }}；</span>
          </div>
        </div>
        <a-input v-else v-model="record.attribute" placeholder="请输入"></a-input>
      </template>
      <template #supplierSpecsTitle>
        <span class="required-ico">*</span>供应商规格
        <a-tooltip placement="top">
          <template slot="title">
            <span>10 表示供应商 1 售卖单元中包含的10个pcs</span>
          </template>
          <a-icon type="info-circle" />
        </a-tooltip>
      </template>
      <template #supplierSpecsSlot="text, record, index">
        <div v-if="record.type == 1">{{ record.specsSup }}个/pcs</div>
        <div v-else>
          <a-form-model-item
            :prop="'tableData.' + index + '.specsSup'"
            :rules="{
              required: true,
              message: '供应商规格不能为空',
              trigger: 'blur',
            }"
          >
            <a-input-number
              v-model="record.specsSup"
              :min="0"
              :step="1"
              :precision="0"
              :max="999999"
              placeholder="请输入"
            />
            个/pcs
          </a-form-model-item>
        </div>
      </template>
      <template #mySpecsTitle>
        <span class="required-ico">*</span>入库规格
        <a-tooltip placement="top">
          <template slot="title">
            <span>2 表示公司将2pcs作为1个售卖单元</span>
          </template>
          <a-icon type="info-circle" />
        </a-tooltip>
      </template>
      <template #mySpecsSlot="text, record, index">
        <div v-if="record.type == 1">{{ record.specsMy }}个/pcs</div>
        <div v-else>
          <a-form-model-item
            :prop="'tableData.' + index + '.specsMy'"
            :rules="{
              required: true,
              message: '入库规格不能为空',
              trigger: 'blur',
            }"
          >
            <a-input-number
              v-model="record.specsMy"
              :min="0"
              :step="1"
              :precision="0"
              :max="999999"
              placeholder="请输入"
            />
            个/pcs
          </a-form-model-item>
        </div>
      </template>
      <template #lowCountSlot="text, record">
        <div v-if="record.type == 1">{{ record.lowCount }}个</div>
        <div v-else>
          <a-input-number v-model="record.lowCount" :min="1" :step="1" :precision="0" placeholder="请输入" />
        </div>
      </template>
      <template #articleNoSlot="text, record">
        <a-input v-model="record.articleNo" placeholder="请输入"></a-input>
      </template>
      <template #unitPriceSlot="text, record">
        <a-input-number v-model="record.unitPrice" :min="0" :step="1" :precision="2" placeholder="请输入" />
      </template>
      <template #daysSlot="text, record">
        <a-input-number v-model="record.days" :min="1" :step="1" placeholder="请输入" />
      </template>
      <template #infoFileSlot="text, record">
        <j-upload-oss v-model="record.infoFile" fileType="file" :number="1" />
      </template>
      <span slot="action" slot-scope="text, record, index">
        <div v-if="record.type == 1">
          <a
            @click="
              defaultLink = record.url
              editIndex = index
              show1688Modal = true
            "
            >重新解析</a
          >
        </div>
        <a @click="delSupplier(index, record)">删除</a>
      </span>
    </a-table>
    <!-- 1688弹窗 -->
    <supplier-1688-modal
      v-if="show1688Modal"
      :visible.sync="show1688Modal"
      :defaultLink="defaultLink"
      @submit="submit1688Modal"
    />
    <supplier-other-modal v-if="showOtherModal" :visible.sync="showOtherModal" />
  </a-form-model>
</template>

<script>
import Sortable from 'sortablejs'
import copyToClipboard from 'copy-to-clipboard'
import { getAction } from '@/api/manage'

import Supplier1688Modal from '@/components/business/Supplier1688Modal.vue'
import SupplierOtherModal from './SupplierOtherModal.vue'

export default {
  components: { Supplier1688Modal, SupplierOtherModal },
  props: {
    // 要编辑的产品档案采购信息
    defaultData: {
      type: Object,
    },
  },
  data() {
    return {
      show1688Modal: false,
      editIndex: null,
      defaultLink: '',
      showOtherModal: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      formData: {
        buyer: '',
        remark: '',
        tableData: [],
      },
      formColumns: [
        {
          title: '排序',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'sortSlot' },
        },
        {
          title: '默认',
          width: 60,
          align: 'center',
          slots: { title: 'defaultTitle' },
          scopedSlots: { customRender: 'defaultSlot' },
        },
        {
          title: '类型',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'typeSlot' },
        },
        {
          align: 'center',
          width: 180,
          slots: { title: 'nameTitle' },
          scopedSlots: { customRender: 'nameSlot' },
        },
        {
          title: '采购链接',
          align: 'left',
          width: 300,
          scopedSlots: { customRender: 'linkSlot' },
        },
        {
          title: '属性',
          align: 'left',
          width: 200,
          scopedSlots: { customRender: 'attrSlot' },
        },
        {
          align: 'center',
          width: 180,
          slots: { title: 'supplierSpecsTitle' },
          scopedSlots: { customRender: 'supplierSpecsSlot' },
        },
        {
          align: 'center',
          width: 180,
          slots: { title: 'mySpecsTitle' },
          scopedSlots: { customRender: 'mySpecsSlot' },
        },
        {
          title: '最低起订量',
          width: 160,
          align: 'center',
          scopedSlots: { customRender: 'lowCountSlot' },
        },
        {
          title: '供应商货号',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'articleNoSlot' },
        },
        {
          title: '采购单价(元）',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'unitPriceSlot' },
        },
        {
          title: '采购交期(天)',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'daysSlot' },
        },
        {
          title: '供应商资料包',
          align: 'center',
          width: 250,
          scopedSlots: { customRender: 'infoFileSlot' },
        },
        {
          title: '操作',
          align: 'center',
          width: 90,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        querySupplier: '/hzkj-product/product/productLibrary/supplier/queryById',
      },
    }
  },
  watch: {
    defaultData: {
      handler(val) {
        // 只要有值就赋值给formData
        if (val) {
          const newData = JSON.parse(JSON.stringify(val)) // 深拷贝，避免直接引用导致数据污染
          this.formData = {
            buyer: newData.other.buyer,
            remark: newData.other.remark,
            tableData: newData.buyers
              .sort((a, b) => a.sortNum - b.sortNum)
              .map((i) => ({
                ...i,
                attribute: i.type == 1 ? JSON.parse(i.attribute) : i.attribute, // 如果是1688供应商，解析属性
              })),
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    optionDiy(result) {
      return result.records.map((item) => {
        return {
          ...item,
          value: item.id,
          text: item.name,
        }
      })
    },
    setDefault(index) {
      this.formData.tableData = this.formData.tableData.map((item, idx) => ({
        ...item,
        izDefault: idx == index ? 1 : 0,
      }))
    },
    addOtherSupplier() {
      this.formData.tableData.push({
        sortNum: new Date().getTime(),
        type: 2, // 其他供应商
        izDefault: this.formData.tableData.some((item) => item.izDefault) ? 0 : 1, // 如果没有默认供应商，则设置为默认
        supplierId: '',
        specsSup: 1,
        specsMy: 1,
        url: '',
        attribute: '',
        lowCount: '',
        articleNo: '',
        unitPrice: '',
        days: '',
        infoFile: '',
      })
    },
    delSupplier(index, record) {
      this.formData.tableData.splice(index, 1)
      if (record.izDefault == 1 && this.formData.tableData.length) {
        // 如果删除的是默认的，自动把第一个设为默认
        this.formData.tableData[0].izDefault = 1
      }
    },
    submit1688Modal(form1688) {
      if (this.defaultLink) {
        this.$set(this.formData.tableData, this.editIndex, {
          ...this.formData.tableData[this.editIndex],
          supplierId: form1688.id,
          name: form1688.name,
          specsSup: form1688.specsSup,
          specsMy: form1688.specsMy,
          proName: form1688.productInfo.subject,
          url: form1688.url,
          attribute: form1688.attrList,
          lowCount: form1688.productInfo.productSaleInfo.minOrderQuantity,
          specId: form1688.specId,
          offerId: form1688.productInfo.openOfferId,
        })
      } else {
        this.formData.tableData.push({
          sortNum: new Date().getTime(),
          type: 1, // 1688供应商
          izDefault: this.formData.tableData.some((item) => item.izDefault) ? 0 : 1, // 如果没有默认供应商，则设置为默认
          supplierId: form1688.id,
          name: form1688.name,
          specsSup: form1688.specsSup,
          specsMy: form1688.specsMy,
          proName: form1688.productInfo.subject,
          url: form1688.url,
          attribute: form1688.attrList,
          lowCount: form1688.productInfo.productSaleInfo.minOrderQuantity,
          specId: form1688.specId,
          offerId: form1688.productInfo.openOfferId,
          articleNo: '',
          unitPrice: '',
          days: '',
          infoFile: '',
        })
      }
    },
    // 复制到剪贴板
    copyTo(value) {
      try {
        copyToClipboard(value)
        this.$message.success('已复制链接')
      } catch (e) {
        this.$message.error('复制失败')
      }
    },
    supplierNameChange(record, [val, oldVal, item]) {
      record.name = item.text // 更新供应商名称
      //查询供应商是否在黑名单
      getAction(this.url.querySupplier, {
        id: val,
      }).then((res) => {
        if (res.success) {
          if (res.result.supplierStatus == 1) {
            this.$confirm({
              content: (h) => {
                return h(
                  'div',
                  {
                    domProps: {
                      innerHTML: `<div style="padding-left: 40px;"><span style="font-weight: bold;">您选择的供应商当前处于黑名单中</span>，还要继续添加吗？</div>`,
                    },
                  },
                  []
                )
              },
              onCancel: () => {
                record.name = ''
                record.supplierId = ''
              },
            })
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
  },
  mounted() {
    //初始化表格拖动
    this.$nextTick(() => {
      new Sortable(this.$refs.buyerTable.$el.querySelector('tbody'), {
        handle: '.sort-handler-ico',
        animation: 200,
        sort: true,
        onEnd: ({ newIndex, oldIndex }) => {
          //  oldIndex:谁
          //  newIndex:移动到哪儿
          const currRow = this.formData.tableData.splice(oldIndex, 1)[0]
          this.formData.tableData.splice(newIndex, 0, currRow)
        },
      })
    })
  },
}
</script>

<style scoped lang="less">
.required-ico {
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
}

.supplier-table {
  margin-top: 20px;
  /deep/ .ant-form-item {
    margin-bottom: 0;

    .ant-form-item-children {
      display: flex;
    }

    .ant-select {
      width: 170px !important;
    }
  }
}
.sort-handler-ico {
  padding: 10px;
  cursor: move;
}
.link-item {
  display: flex;
  .link {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 180px;
  }
}
.copy-btn {
  height: 18px;
  margin-left: 5px;
}
</style>
